﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using WorkFlowCore.Authorization;
using WorkFlowCore.Authorization.JWT;
using WorkFlowCore.Framework.Migrations;
using WorkFlowCore.Framework.UserSelectors;
using WorkFlowCore.Host.ViewModels.Account;
using WorkFlowCore.IRepositories;
using WorkFlowCore.Resources;
using WorkFlowCore.Workflows;

namespace WorkFlowCore.Host.Controllers
{
    /// <summary>
    /// 账号管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class ResourceController : AbpControllerBase
    {
        
        private readonly IResourceManager resourceManager;

        public ResourceController(IResourceManager resourceManager)
        {
            this.resourceManager = resourceManager;
        }


        /// <summary>
        /// 上传
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost("Upload")]
        public async Task<ResourceInfo> Upload([FromForm] IFormFile[] formFiles, [FromForm] string path)
        {
            if(formFiles==null || formFiles.Length!=1)
            {
                throw new ArgumentException("请选择一个文件");
            }

            var formFile = formFiles[0];
            if(formFile.Length > 1048576)
            {
                throw new ArgumentException("最大只能传 1M");
            }

            var length = formFile.Length;
            var fileName = formFile.FileName;
            var data = formFile.GetAllBytes();
            var result = await resourceManager.Upload(data,fileName,path);
            if(result == null)
            {
                throw new Exception("上传异常");
            }
            return result;
        }


        /// <summary>
        /// 下载
        /// </summary>
        /// <returns></returns>
        [HttpGet("Download")]
        [AllowAnonymous]
        public async Task<ActionResult> Download(string fileId)
        {
            var resourceInfo = await resourceManager.GetResourceInfo(fileId);
            var fileData = await resourceManager.Download(resourceInfo);
            return File(fileData, "application/octet-stream", resourceInfo.Name);
        }

        /// <summary>
        /// 获取文件信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetResourceInfo")]
        public async Task<ResourceInfo> GetResourceInfo(string fileId)
        {
            return await resourceManager.GetResourceInfo(fileId);
        }

    }
}
